var User=function () {

    bootbox.setDefaults({
        'locale':'zh_CN'
    });

    $.fn.serializeObject = function () {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function () {
            if (o[this.name]) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };

    return{
        initUpload:function(){
            $("#files").fileinput({
                showPreview: true,
                showUpload: true,
                theme: "explorer",
                language: 'zh',
                elErrorContainer: '#kartik-file-errors',
                allowedFileExtensions: ["jpg", "png", "gif"],
                showCaption: false,
                dropZoneEnabled: false,
                maxFileSize: 2*1024,
                minFileCount: 1,
                maxFileCount: 1,
                browseClass: "btn btn-primary",
                enctype: 'multipart/form-data',
                validateInitialCount:true,
                uploadUrl: '/api/upload',
                previewFileIconSettings: { // configure your icon file extensions
                    'doc': '<i class="fa fa-file-word-o text-primary"></i>',
                    'xls': '<i class="fa fa-file-excel-o text-success"></i>',
                    'ppt': '<i class="fa fa-file-powerpoint-o text-danger"></i>',
                    'pdf': '<i class="fa fa-file-pdf-o text-danger"></i>',
                    'zip': '<i class="fa fa-file-archive-o text-muted"></i>',
                    'htm': '<i class="fa fa-file-code-o text-info"></i>',
                    'txt': '<i class="fa fa-file-text-o text-info"></i>',
                    'dat': '<i class="fa fa-file-text-o text-info"></i>',
                    'mov': '<i class="fa fa-file-movie-o text-warning"></i>',
                    'mp3': '<i class="fa fa-file-audio-o text-warning"></i>',
                    'jpg': '<i class="fa fa-file-photo-o text-danger"></i>',
                    'gif': '<i class="fa fa-file-photo-o text-warning"></i>',
                    'png': '<i class="fa fa-file-photo-o text-primary"></i>'
                }
            }).on("fileuploaded", function (event, data, previewId, index) {
                var response=data.response;
                if(response != undefined && response.code =='200'){
                    console.log(response.data[0].filePath)
                    $('#img').val("/userImg/"+response.data[0].filePath)
                    $("#files").fileinput('reset');
                }
            });
        },

        init:function () {
            $('#userForm').bootstrapValidator({
                message: '该值无效',
                trigger: 'blur keyup',
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    /*验证：规则*/
                    username: {
                        validators: {
                            notEmpty: {
                                message: '用户名不能为空'
                            }
                        }
                    },
                    password: {
                        validators: {
                            notEmpty: {
                                message: '密码不能为空'
                            },
                            stringLength: {
                                min: 6,
                                max: 19,
                                message: '新密码长度大于5小于20'
                            },
                            regexp: {
                                regexp: /^[^ ]+$/,
                                message: '新密码不能有空格'
                            }
                        }
                    },
                    sex: {
                        validators: {
                            notEmpty: {
                                message: '性别不能为空'
                            }
                        }
                    },
                    phone: {
                        validators: {
                            notEmpty: {
                                message: '电话不能为空'
                            }
                        }
                    },
                    address: {
                        validators: {
                            notEmpty: {
                                message: '地址不能为空'
                            }
                        }
                    },idCard: {
                        validators: {
                            notEmpty: {
                                message: '身份证不能为空'
                            }
                        }
                    },roleIds: {
                        validators: {
                            notEmpty: {
                                message: '角色不能为空'
                            }
                        }
                    }

                }
            }).on('error.field.bv', function (e, data) {//‘用户确认密码’ 没输入的时候，‘用户新密码’不提示‘用户新密码与确认密码不一致’
                if (data.field == 'newPassword') {
                    var len1 = data.element.val().length;
                    var len2 = $('#comfirmPassword').val().length;
                    var k = data.element.val().indexOf(" ");
                    if (len1 > 5 && len2 < 6 && k < 0) {
                        var $parent = data.element.parents('.form-group');
                        $parent.removeClass('has-error');
                        $parent.find('.form-control-feedback[data-bv-icon-for="' + data.field + '"]').hide();
                        data.element.siblings('[data-bv-validator="identical"]').hide();
                    }
                }
            });
        },
        showAdduser:function(){
            $('#addUser').modal({
                show:true
            });
            $('#div_pwd').show();
            $('#addUser h4').text("添加用户");
            User.init();
        },
        saveUser:function () {
            $('#userForm').bootstrapValidator('validate');
            var bootstrapValidator = $("#userForm").data('bootstrapValidator');
            if(bootstrapValidator.isValid()){
                var data = $('#userForm').serializeObject();
                $.ajax({
                    url: "/api/user/save",
                    data:JSON.stringify(data),
                    type:'POST',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        if(data.code =='401'){
                            bootbox.alert(data.message);
                        }else{
                            if(data.data){
                                $('#userTable').dataTable().fnDraw();
                                $('#userForm')[0].reset();
                                $('#addUser').modal("hide");
                            }else{
                                bootbox.alert(data.message)
                            }
                        }
                    }
                });
            }
        },
        getUser:function (id) {
            $.ajax({
                url: "/api/user/getUser",
                data:{id:id},
                type:'POST',
                dataType: "json",
                success: function (data) {
                    if(data.code =='401'){
                        bootbox.alert(data.message);
                    }else if(data.code =='200'){
                        $('#div_pwd').hide();
                        Form.loadData(data.data);
                        $('#addUser').modal({
                            show:true
                        });
                        $('#addUser h4').text("编辑用户");
                    }
                }
            });
        },
        deleteUser:function (id) {
            bootbox.confirm('确定要删除该用户吗?',function(btn){
                if(btn){
                    $.ajax({
                        url: "/api/user/delete",
                        data:{id:id},
                        type:'POST',
                        dataType: "json",
                        success: function (data) {
                            if(data.code =='401'){
                                bootbox.alert(data.message);
                            }else if(data.code =='200'){
                                $('#userTable').dataTable().fnDraw();
                            }
                        }
                    });
                }
            });
        },
        restPwd:function(id){
            bootbox.confirm('确定要重置该用户的密码吗? 重置密码为：123456',function(btn){
                if(btn){
                    $.ajax({
                        url: "/api/user/restPwd",
                        data:{id:id},
                        type:'POST',
                        dataType: "json",
                        success: function (data) {
                            if(data.code =='401'){
                                bootbox.alert(data.message);
                            }else if(data.code =='200' && data.data){
                                bootbox.alert(data.message);
                            }else {
                                bootbox.alert(data.message);
                            }
                        }
                    });
                }
            });
        },
        formReset:function(){
            $('#userForm')[0].reset();
            $('#div_pwd').hide();
            $('#id').val('');
            $('#img').val('');
            $(':input','#userForm').removeAttr('checked');
            $('#userForm').bootstrapValidator('destroy');
            $("#userForm").data('bootstrapValidator',null);

            $("#files").fileinput('reset');
        }
    }
}();